﻿Imports System.Data.OleDb

Public Class AddNewCar
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub btn_cancel_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btn_cancel.Click

        tb_name.Text = ""
        tb_frame.Text = ""
        tb_body.Text = ""
        tb_brakes.Text = ""
        tb_engine.Text = ""
        tb_model.Text = ""
        tb_stering.Text = ""
        tb_suspension.Text = ""
        tb_tires.Text = ""
        tb_topspeed.Text = ""

    End Sub

    Protected Sub btn_add_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btn_add.Click

        If tb_name.Text = "" Then
            lbl_error.Visible = True
            lbl_name.Visible = True
            Return
        End If

        If tb_model.Text = "" Then
            lbl_error.Visible = True
            lbl_model.Visible = True
            Return
        End If

        If Not fu_url.HasFile Then
            lbl_error.Text = "Please chose an image"
            lbl_error.Visible = True
            Return
        End If

        Dim fileName As String
        fileName = Guid.NewGuid().ToString() & "." & getSuffix(fu_url.FileName)
        If fu_url.HasFile Then
            fu_url.SaveAs(Server.MapPath("Images") & "/" & fileName)
        End If


        Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
        Dim sql As String = "insert into cars (cName,cModel,cImage,Frame,Body,Suspension,Brakes,Stering,Tires,Engine,Topspeed) values(@f1,@f2,@f3,@f4,@f5,@f6,@f7,@f8,@f9,@f10,@f11)"
        conn.Open()

        Dim cmd As OleDbCommand = New OleDbCommand(sql, conn)
        cmd.Parameters.AddWithValue("@f1", tb_name.Text.ToString())
        cmd.Parameters.AddWithValue("@f2", tb_model.Text.ToString())
        cmd.Parameters.AddWithValue("@f3", "Images/" & fileName)
        cmd.Parameters.AddWithValue("@f4", tb_frame.Text.ToString())
        cmd.Parameters.AddWithValue("@f5", tb_body.Text.ToString())
        cmd.Parameters.AddWithValue("@f6", tb_suspension.Text.ToString())
        cmd.Parameters.AddWithValue("@f7", tb_brakes.Text.ToString())
        cmd.Parameters.AddWithValue("@f8", tb_stering.Text.ToString())
        cmd.Parameters.AddWithValue("@f9", tb_tires.Text.ToString())
        cmd.Parameters.AddWithValue("@f10", tb_engine.Text.ToString())
        cmd.Parameters.AddWithValue("@f11", tb_topspeed.Text.ToString())

        cmd.ExecuteNonQuery()

        conn.Close()

        Response.Redirect("Default.aspx")

    End Sub

    Function getSuffix(ByVal fn As String)
        Dim fileparts = fn.Split(".")
        Dim suffix = fileparts(fileparts.Length - 1)
        Return suffix
    End Function
End Class